# 操作Redis对话记录
import json

from bot.insurance_planner_gpt.db.redis.HzAsyncRedisHelper import HzAsyncRedisHelper

SESSION_EXPIRE_SECONDS = 1800
LLM_RESULT_EXPIRE_SECONDS = 30

hzAsyncRedisHelper = HzAsyncRedisHelper()


class HzDialogueStorage:
    _instance = None
    _is_init = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(HzDialogueStorage, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if HzDialogueStorage._is_init:
            return
        self.DIALOGUE_SESSION = "dialogueSession:"
        self.LLM_RESULT_PREFIX = "llmResult:"
        self.PLANNER_ADD_WECHAT_REDIS_KEY_PREFIX = "planner_add_wechat:"
        self.TELE_WECHAT_SKILL_HANGUP = "tele_wechat_skill_hangup:"
        self.IS_ADD_WECHAT = "is_add_wechat:"
        pass

    async def mq_error_data(self, msg):
        await hzAsyncRedisHelper.setListRightPush("MQ_ERROR_DATA", json.dumps(msg, ensure_ascii=False))

    async def mq_error_data_pop(self):
        return await hzAsyncRedisHelper.getListLeftPop("MQ_ERROR_DATA")

    def get_tele_wechat_skill_hangup_key(self, sessionId):
        return self.PLANNER_ADD_WECHAT_REDIS_KEY_PREFIX + self.TELE_WECHAT_SKILL_HANGUP + sessionId

    async def get_tele_wechat_skill_hangup(self, sessionId):
        key = self.get_tele_wechat_skill_hangup_key(sessionId)
        value = await hzAsyncRedisHelper.get(key)
        if value is not None:
            return value.decode('utf-8')
        else:
            return None

    async def set_tele_wechat_skill_hangup(self, sessionId, data):
        key = self.get_tele_wechat_skill_hangup_key(sessionId)
        await hzAsyncRedisHelper.set_time(key, data, SESSION_EXPIRE_SECONDS)

    async def del_tele_wechat_skill_hangup(self, sessionId):
        key = self.get_tele_wechat_skill_hangup_key(sessionId)
        await hzAsyncRedisHelper.delete(key)

    def get_is_add_wechat_key(self, sessionId):
        return self.PLANNER_ADD_WECHAT_REDIS_KEY_PREFIX + self.IS_ADD_WECHAT + sessionId

    async def get_is_add_wechat(self, sessionId):
        key = self.get_is_add_wechat_key(sessionId)
        value = await hzAsyncRedisHelper.get(key)
        if value is not None:
            return value.decode('utf-8')
        else:
            return None

    async def set_is_add_wechat(self, sessionId, data):
        key = self.get_is_add_wechat_key(sessionId)
        await hzAsyncRedisHelper.set_time(key, data, SESSION_EXPIRE_SECONDS)

    async def del_is_add_wechat(self, sessionId):
        key = self.get_is_add_wechat_key(sessionId)
        await hzAsyncRedisHelper.delete(key)


if __name__ == '__main__':
    # dialogue_storage.get_dialogue_session('0-2199-665498914-1666618255712043008-1264', 55369)
    pass
